# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import base64
import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose , json, leggiInSessione
from lib.utils import mN, prep2json
from random import randint as rint
import Environment

@expose('/pg/ac_ParametriExport/<action>')
@expose('/pg/ac_ParametriExport/')
@expose('/pg/ac_ParametriExport')
def anagraficaParametriExport(req, action=None):
    """
  id serial NOT NULL,
  denominazione_breve character varying(10) NOT NULL,
  denominazione character varying(100) NOT NULL,
  id_tipo integer NOT NULL,
    """

    def __show__(req, action=None):
        pageData = {'file': "/pg/ac_ParametriExport"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        from dao.ParametriExport import ParametriExport
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione = req.form.get("fk_denominazione")
        daos = ParametriExport().select(denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = ParametriExport().count(denominazione=fk_denominazione,
                                    batchSize=None)
        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        from dao.ParametriExport import ParametriExport
        from dao.Organization import Organization
        id = req.form.get("id")
        if id:
            d = ParametriExport().getRecord(id=int(id))
        else:
            d = ParametriExport()

        pageData = {'file': "pg/addedit/ae_parametri_export",
                    "dao": d,
                    "orgs": Organization().select(batchSize=None)
                    }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate
        #Column('tipo_destinazione',String(20), nullable=True),
        #Column('denominazione', String(500), nullable=False),
        #Column('url_destinazione', String(200), nullable=True),
        #Column('owner_org', String(20), nullable=True),
        #Column('azione',String(20), nullable=True),
        #Column('apikey', String(20), nullable=True),
        Column('descrizione', Text, nullable=True),


        """
        from dao.ParametriExport import ParametriExport
        id = req.form.get("id")
        if id != "None":
            d = ParametriExport().getRecord(id=int(id))
        else:
            d = ParametriExport()
        d.denominazione = str(req.form.get("denominazione"))
        d.tipo_destinazione = str(req.form.get("tipo_destinazione"))
        d.url_destinazione = str(req.form.get("url_destinazione"))
        d.id_organization = int(req.form.get("id_organization"))
        d.azione = str(req.form.get("azione"))
        d.apikey = str(req.form.get("apikey"))
        d.descrizione = str(req.form.get("descrizione"))
        d.persist()
        url_red = "/pg/ac_ParametriExport/"
        return Page(req).redirect(url_red)

    def __delete__(req, action=None):
        """Cancella una riga"""
        from dao.ParametriExport import ParametriExport
        id = int(req.form.get("id"))
        d = ParametriExport().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)


    def __preview__(req, action=None):
        from dao.ParametriExport import ParametriExport
        id = int(req.form.get("id"))
        d = ParametriExport().getRecord(id=id)
        pageData = {'file': "/pg/parametri_export",
                    "dao": d}
        return Page(req).render(pageData)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    elif action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    else:
        return __show__(req, action=action)
